$(function(){
    paginationInit();
});

var paginationMaxLength=8;//分页栏的最大显示条数
var onlyOnePageIsShow = true;//只有一页的时候是否显示
function paginationInit(){
    $('[am-pagination =pagination_new ]').each(function(){
        initPagination($(this));
    });
}

function initPagination(element){

    element.html('');
    var pagenumber = element.attr('pagenumber');
    var totalpage = element.attr('totalpage');
    var pMaxLength = element.attr('paginationMaxLength');
    var onePageIsShow = element.attr('onlyOnePageIsShow');
    // console.log(totalpage)
    if(isNeedPagination(Number(totalpage),onePageIsShow)){
        var content = '<ul class="am-pagination am-pagination-centered"><li value="0"><a href="javascript:void(0);">«</a></li>';
        for(var i =1; i<=totalpage;i++){
            content +='<li value="'+i+'"><a href="javascript:void(0);">'+i+'</a></li>'
        }
        content +='<li value="-1"><a href="javascript:void(0);">»</a></li></ul>';
        element.append(content);
        element.children('ul').children('li[value='+pagenumber+']').attr('class','am-active');
        setDisplayMaxLength(element,pMaxLength);
        addClickListener(element);
    }
}

function setDisplayMaxLength(element,len){
    var currentpage =  Number(element.attr('pagenumber'));
    var totoalpage = Number(element.attr('totalpage'));
    if(checkParamIsPositiveInteger(len)){
        len = Number(len);
    }else{
        len =paginationMaxLength;
    }
    if(len<totoalpage){
        var temp1 = parseInt((len-1)/2);
        var temp2 = parseInt(len/2);
        if(temp1<temp2){
            var leftstart = currentpage - temp1;
            var rightend = currentpage + temp1 + 1;
        }else{
            var leftstart = currentpage - temp1;
            var rightend = currentpage + temp1;
        }
        if(leftstart<1){
            rightend +=(1-leftstart);
            leftstart = 1;
        }
        if(rightend>totoalpage){
            if(leftstart>1){
                leftstart -=(rightend-totoalpage);
            }
            rightend =totoalpage;
        }
        if(leftstart<1){
            leftstart=1
        }
        while(leftstart >1){
            element.children('ul').children('li[value = '+(--leftstart)+']').css('display','none');
        }
        while(rightend <totoalpage){
            element.children('ul').children('li[value = '+(++rightend)+']').css('display','none');
        }
    }
}

function isNeedPagination(totalpage,settingfromHTML){
    var condition ;
    if(settingfromHTML == "true"){
        condition = true;
    }else if(settingfromHTML == 'false'){
        condition = false;
    }else {
        condition = onlyOnePageIsShow;
    }
    if(condition && totalpage<1){
        return false;
    }else if(!condition && totalpage<=1){
        return false;
    }
    return true;
}
//根据页面pagenumber、my_totoalpage更新分页，参数element传的是分页的容器

function addClickListener(element){
    element.children('ul').children('li').bind('click',function(){
        var temp = Number($(this).attr('value'));
        var pagenumber = Number($(this).parent().parent().attr('pagenumber'));
        var totalpage = Number($(this).parent().parent().attr('totalpage'));
        if(temp == 0){
            temp = pagenumber-1;
        }else if(temp == -1){
            temp = pagenumber+1;
        }
        if(temp != pagenumber && temp !=0 && temp<=totalpage){
            $(this).parent().parent().attr('pagenumber',temp);
            paginationClick(element.attr("id"));
            initPagination(element);
        }
        return false;
    })
}
function checkParamIsPositiveInteger(param){
    var reg = /^[1-9]+[0-9]*]*$/;
    return reg.test(param);
}

//用户需要自己实现的点击事件，参数为分页容器的id
function paginationClick(pagination_id){
    var pagenumber = $('#'+pagination_id+'').attr('pagenumber');
    var totalpage = $('#'+pagination_id+'').attr('totalpage');
    // console.log(temp);
    // console.log(pagenumber);
    JSON.stringify(pagenumber);
    $.ajax({
        type:"POST",
        url:constUrl+"MonitorHostServlet",
        dataType:"json",
        data: {
            operateType: "showPaged",
            onePageCount: "10",
            currentPage: pagenumber
        },
        success:function(data){
            addBox(data.datas);
        },
        error:function () {
            console.log(pagenumber);
        }
    });
}

function editHost(hostId){
    layer.ready(function() {
        //官网欢迎页
        layer.open({
            type: 2,
            skin: 'layui-layer-lan',
            title: '修改主机信息',
            fix: false,
            shadeClose: true,
            maxmin: true,
            area: ['450px', '600px'],
            content: constUrl+'views/monhost/update.action?id='+hostId
        });
    });
}
function addBox(data){
    $("tr").remove(".addTr");
    console.log(data)
    for(var i=0;i<data.length;i++) {
        $("#hostGroupTableList").append(
            "<tr id="+data[i].hostId+" class='addTr'>" +
            "<td>"+(i+1)+"</td>"+
            '<td><input type="checkbox" tr-checkbox value="' + data[i].hostId + '"></td>'+
            "<td>"+data[i].hostName+"</td>"+
            "<td>"+data[i].hostIp+"</td>"+
            "<td>"+data[i].hostGroupIds+"</td>"+
            "<td>"+data[i].hostMac+"</td>"+
            "<td title='"+data[i].introduction+"'>"+data[i].introduction+"</td>"+
            "<td><div class=\"am-btn-toolbar\">"+
            "<div class=\"am-btn-group am-btn-group-xs \">"+
            "<button class=\"am-btn am-btn-default am-btn-xs am-text-success am-hide-sm-only\" onclick=\"editHost('"+data[i].hostId+"')\">"+
            "<span class=\"am-icon-pencil-square-o\"></span>修改</button>"+
            "<button class=\"am-btn am-btn-default am-btn-xs am-text-danger am-hide-sm-only\" onclick=\"deleteHost('"+data[i].hostId+"')\">"+
            "<span class=\"am-icon-trash-o\"></span>删除</button>"+
            "</div></div></td>" +
            "</tr>"
        );
    }
}
function addHost() {
    layer.ready(function() {
        //官网欢迎页
        layer.open({
            type: 2,
            skin: 'layui-layer-lan',
            title: '添加主机',
            fix: false,
            shadeClose: true,
            maxmin: true,
            area: ['450px', '600px'],
            content:constUrl+'views/monhost/add.action'
        });
    });
}
$('#checkAll').click(function () {
    let check_list = $("input[tr-checkbox]");
    let current = $("#checkAll");
    if (current.is(':checked')){
        for (let i = 0; i < check_list.length; i++){
            check_list.eq(i).prop("checked",true);
        }
    } else {
        for (let i = 0; i < check_list.length; i++){
            check_list.eq(i).removeAttr('checked');
        }
    }
});
// 删除列表内容
function deleteHost(hostId){
    var index = parent.layer.getFrameIndex(window.name);
    layer.confirm('确定要删除吗？', {
        btn: ['确定','取消'] //按钮
    }, function(){
        $.ajax({
            type:"POST",
            url:constUrl+"MonitorHostServlet",
            dataType:"json",
            data: {
                operateType:"delete",
                hostId:hostId
            },
            success:function(responseText){
                // layer.msg('删除成功', {icon: 1,time: 1000,});
                // parent.location.reload(index);
                layer.confirm('删除成功！',{
                    btn:['确定']
                },function () {
                    parent.location.reload(index);
                })
            },
            error:function(responseText) {
                layer.msg('删除失败')
            },
        })
    }, function(){
        layer.msg('取消删除', {
            time: 1000 //1s后自动关闭

        });
    });
}
// 批量删除
function deleteHosts(){
    var index = parent.layer.getFrameIndex(window.name);
    let hostIds = "";
    $("input[tr-checkbox]").each(function () {
        if ($(this).prop("checked")) {
            hostIds += $(this).attr('value') + ',';
        }
    });
    hostIds = hostIds.substring(0, hostIds.length-1);
    layer.confirm('确定要批量删除选中的主机吗？', {
        btn: ['确定','取消'] //按钮
    }, function(){
        $.ajax({
            type:"POST",
            url:constUrl+"MonitorHostServlet",
            dataType:"json",
            data: {
                operateType:"deletes",
                hostIds:hostIds
            },
            success:function(responseText){
                // layer.msg('删除成功', {icon: 1,time: 1000,});
                // parent.location.reload(index);
                layer.confirm('删除成功！',{
                    btn:['确定']
                },function () {
                    parent.location.reload(index);
                })
            },
            error:function(responseText) {
                layer.msg('删除失败')
            },
        })
    }, function(){
        layer.msg('取消删除', {
            time: 1000 //1s后自动关闭
        });
    });
}